<template>
  <GlobalContainer className="flex flex-col !bg-[#F4F5F8]" :backgroundImage="`${OSS_URL}/images/baoxiu/head_bg.png`">
    <GlobalHeader title="物业+居家养老" showBack :backgroundImage="`${OSS_URL}/images/baoxiu/head_bg.png`" :fixed="true" />
    <div class="pb-150">
      <div class="header-c">
        <div class="swiper-c">
          <wd-swiper height="340rpx" :list="swiperList" autoplay v-model:current="swiperCurrent" />
        </div>
        <div class="price-c px-32 py-16">
          <div class="line1">优惠价</div>
          <div class="line2">
            {{ goodsDetail.salePrice }}<span v-if="goodsDetail.unit">/{{ goodsDetail.unit }}</span>
          </div>
        </div>
      </div>

      <div class="specification-c">
        <div class="title">{{ goodsDetail.title }}</div>
        <div class="subtitle mb-16 py-16">{{ goodsDetail.subtitle }}</div>
        <!-- 判断是否绑定房源， 绑定房源显示选择房源组件 -->
        <div class="item-c flex items-center" @tap="roomShow = true" v-if="roomList.length > 0">
          <div class="label">地址</div>
          <div class="value">{{ formatRoom(currentRoom) }}</div>
          <div class="right ml-auto"><wd-icon name="arrow-right" size="16px" color="#606266" /></div>
        </div>
        <div class="item-c flex items-center" @tap="addressShow = true" v-else>
          <div class="label">地址</div>
          <div class="value">{{ address || '请选择地址' }}</div>
          <div class="right ml-auto"><wd-icon name="arrow-right" size="16px" color="#606266" /></div>
        </div>
        <div class="item-c flex items-center" @tap="phoneShow = true">
          <div class="label">联系</div>
          <div class="value">{{ phone && contacts ? contacts + ' ' + phone : '请输入联系方式' }}</div>
          <div class="right ml-auto"><wd-icon name="arrow-right" size="16px" color="#606266" /></div>
        </div>
        <div class="item-c flex items-center" @tap="specificationShow = true">
          <div class="label">规格</div>
          <div class="value">
            {{ activeSpecification.specValueNames ? '已选：' + activeSpecification.specValueNames + 'x' + quantity : '请选择规格' }}
          </div>
          <div class="right ml-auto"><wd-icon name="arrow-right" size="16px" color="#606266" /></div>
        </div>
        <div class="item-c">
          <div class="label mb-10 !w-auto">期望服务时间</div>
          <div class="value">
            <div class="mb-10 flex items-center" @tap="showTime('startTime')">
              最早<span class="ml-10 text-[#303133]">{{ startTime ? format(startTime, 'yyyy年MM月dd日 HH点') : '请选择' }}</span>
            </div>
            <div class="flex items-center" @tap="showTime('endTime')">
              最晚<span class="ml-10 text-[#303133]">{{ endTime ? format(endTime, 'yyyy年MM月dd日 HH点') : '请选择' }}</span>
            </div>
          </div>
          <!-- <div class="right ml-auto"><wd-icon name="arrow-right" size="16px" color="#606266" /></div> -->
        </div>
      </div>
      <div class="detail-c mt-24 bg-white px-10 pb-24">
        <div class="title py-24 pl-32">服务详情</div>
        <div class="content">
          <rich-text :nodes="detail" />
        </div>
      </div>
    </div>
    <div class="btn-c px-30 pb-safe py-20">
      <div class="btn" @tap="submit">提交</div>
    </div>
    <wd-action-sheet v-model="specificationShow" title="产品规格">
      <div class="action-sheet-c px-32">
        <div
          class="item-c flex items-center px-32"
          v-for="item in goodsDetail.mallProductSkuList"
          :key="item.id"
          :class="{ active: activeSpecification.id === item.id }"
          @tap="activeSpecification = item"
        >
          <div class="left">{{ item.specValueNames }}</div>
          <div class="right ml-auto">
            <span>{{ item.salePrice }}</span>
            <span>{{ item.unit || goodsDetail.unit || '元' }}</span>
          </div>
        </div>
        <div class="num-c">
          <div class="left">下单数量</div>
          <div class="right ml-auto flex items-center">
            <div class="btn" @tap.stop="subQuantity()">
              <image src="../../static/images/jieyong/sub_icon.png" class="size-36" />
            </div>
            <div class="num">{{ quantity }}</div>
            <div class="btn" @tap.stop="addQuantity()">
              <image src="../../static/images/jieyong/add_icon.png" class="size-36" />
            </div>
          </div>
        </div>
      </div>
      <div class="btn-c px-30 pb-safe py-20">
        <div class="btn" @tap="specificationShow = false">确定</div>
      </div>
    </wd-action-sheet>
    <wd-action-sheet
      v-if="roomList.length > 0"
      v-model="roomShow"
      title="选择房源"
      :actions="roomList"
      @close="roomShow = false"
      @select="roomSelect"
    />
    <wd-action-sheet v-else v-model="addressShow" title="请选择地址">
      <div class="action-sheet-c px-32">
        <wd-cell-group border>
          <wd-col-picker
            label="选择地区"
            v-model="addressForm.area"
            :columns="area"
            :column-change="areaColumnChange"
            @confirm="areaConfirmHandle"
          />
          <wd-input label="详细地址" v-model="addressForm.address" placeholder="请输入详细地址" />
        </wd-cell-group>
      </div>
      <div class="btn-c px-30 pb-safe py-20">
        <div class="btn" @tap="addressSubmit">确定</div>
      </div>
    </wd-action-sheet>
    <wd-action-sheet v-model="timeShow" title="选择时间">
      <div class="action-sheet-c px-32">
        <LDateTimePicker v-if="currentTimeFiled === 'startTime'" v-model="startTime" :start="minDate" :mode="15" @change="timeChange" />
        <LDateTimePicker v-else v-model="endTime" :start="minDate" :mode="15" @change="timeChange" />
      </div>
      <div class="btn-c px-30 pb-safe py-20">
        <div class="btn" @tap="timeShow = false">确定</div>
      </div>
    </wd-action-sheet>

    <wd-action-sheet v-model="phoneShow" title="联系方式">
      <div class="action-sheet-c px-32">
        <wd-cell-group border>
          <wd-input label="联系人" :no-border="false" v-model="phoneNumberForm.contacts" placeholder="请输入联系人" />
          <wd-input
            label="联系电话"
            label-width="100"
            type="number"
            :no-border="false"
            v-model="phoneNumberForm.phone"
            :maxlength="11"
            placeholder="请输入联系电话"
          />
        </wd-cell-group>
      </div>
      <div class="btn-c px-30 pb-safe py-20">
        <div class="btn" @tap="phoneNumberSubmit">确定</div>
      </div>
    </wd-action-sheet>

    <!-- <limeDateTimePicker /> -->
  </GlobalContainer>
</template>

<script setup>
import LDateTimePicker from '@/uni_modules/lime-date-time-picker/components/l-date-time-picker/l-date-time-picker.vue'
// import limeDateTimePicker from '@/uni_modules/lime-date-time-picker/components/lime-date-time-picker/lime-date-time-picker.vue'
import { onLoad } from '@dcloudio/uni-app'
import { useAccountStore } from '@/store'
import { getBuildingListApi } from '@/common/api/base'
import { getProductDetail } from '@/common/api/report'
import { showToast } from '@/utils/index'
import { format } from 'date-fns'
import { formatRoom } from '@/common/format'
import { useColPickerData } from '@/hooks/useColPickerData'
const { colPickerData, findChildrenByCode } = useColPickerData()
const OSS_URL = import.meta.env.VITE_OSS_URL
const swiperList = ref([])
const swiperCurrent = ref(1)
const accountStore = useAccountStore()

const specificationShow = ref(false)
const activeSpecification = ref({})
const quantity = ref(1)
 
// 处理时间， 2天后可选择  + 1 * 24 * 60 * 60 * 1000
const minDate = new Date().getTime()
const timeShow = ref(false)
const startTime = ref(minDate)
const endTime = ref('')
const currentTimeFiled = ref('startTime')
const showTime = type => {
  currentTimeFiled.value = type
  timeShow.value = true
}
const timeChange = value => {
  console.log('value', value)
  // 如果startTime大于endTime，则startTime等于endTime
  if (currentTimeFiled.value === 'startTime') {
    startTime.value = value
    if (endTime.value && startTime.value > endTime.value) {
      startTime.value = endTime.value
    }
  }
  // 如果endTime小于startTime，则endTime等于startTime
  if (currentTimeFiled.value === 'endTime') {
    endTime.value = value
    if (startTime.value && endTime.value < startTime.value) {
      endTime.value = startTime.value
    }
  }
}

const phone = ref('')
const contacts = ref('')
const phoneShow = ref(false)
const phoneNumberForm = ref({
  contacts: '',
  phone: ''
})
const phoneNumberSubmit = () => {
  if (!phoneNumberForm.value.contacts) {
    showToast('请输入联系人')
    return
  }
  if (!phoneNumberForm.value.phone) {
    showToast('请输入联系电话')
    return
  }
  phone.value = phoneNumberForm.value.phone
  contacts.value = phoneNumberForm.value.contacts
  phoneShow.value = false
}

const goodsDetail = ref('') // 商品详情
const detail = ref('') // 描述详情

const currentRoom = ref(accountStore.currentRoom) // 当前房屋
const roomList = ref([]) // 房屋列表
const roomShow = ref(false) // 房屋选择
const addressShow = ref(false) // 地址选择
const address = ref('') // 地址
const addressForm = ref({
  area: [],
  areaStr: '',
  address: ''
})
const addressSubmit = () => {
  address.value = addressForm.value.areaStr + addressForm.value.address
  addressShow.value = false
}

const area = ref([
  colPickerData.map(item => {
    return {
      value: item.value,
      label: item.text
    }
  })
])

const areaColumnChange = ({ selectedItem, resolve, finish }) => {
  const areaData = findChildrenByCode(colPickerData, selectedItem.value)
  if (areaData && areaData.length) {
    resolve(
      areaData.map(item => {
        return {
          value: item.value,
          label: item.text
        }
      })
    )
  } else {
    finish()
  }
}

const areaConfirmHandle = ({ value, selectedItems }) => {
  const area = selectedItems.map(item => item.label).join(' ')
  addressForm.value.areaStr = area
}

const getRoomList = () => {
  getBuildingListApi({}).then(res => {
    roomList.value = res.map(item => ({
      ...item,
      name: formatRoom(item)
    }))
    if (currentRoom.value.id) {
      phoneNumberForm.value.contacts = currentRoom.value.realName
      phoneNumberForm.value.phone = currentRoom.value.phone
      phone.value = currentRoom.value.phone
      contacts.value = currentRoom.value.realName
    }
  })
}
const roomSelect = ({ item }) => {
  currentRoom.value = item
  roomShow.value = false
  phoneNumberForm.value.contacts = item.realName
  phoneNumberForm.value.phone = item.phone
  phone.value = item.phone
  contacts.value = item.realName
}
const subQuantity = () => {
  if (quantity.value === 1) return
  quantity.value--
}
const addQuantity = () => {
  quantity.value++
}
const submit = () => {
  showToast('提交成功')
  if (roomList.value.length > 0 && !currentRoom.value.id) {
    showToast('请选择房源')
    return
  }
  if (roomList.value.length === 0 && address.value === '') {
    showToast('请选择地址')
    return
  }
  if (!phone.value || !contacts.value) {
    showToast('请输入联系方式')
    return
  }
  if (!activeSpecification.value.id) {
    showToast('请选择规格')
    return
  }
  if (!startTime.value || !endTime.value) {
    showToast('请选择服务时间')
    return
  }
  uni.navigateTo({
    url:
      '/subPages/wuye/submit?detail=' +
      JSON.stringify({
        id: goodsDetail.value.id,
        title: goodsDetail.value.title || '',
        currentRoom: currentRoom.value,
        address: address.value,
        phone: phone.value,
        contacts: contacts.value,
        quantity: quantity.value,
        startTime: format(startTime.value, 'yyyy-MM-dd HH:mm'),
        endTime: format(endTime.value, 'yyyy-MM-dd HH:mm'),
        specification: activeSpecification.value
      })
  })
}

const formatter = (type, value) => {
  switch (type) {
    case 'year':
      return value
    case 'month':
      return value
    case 'date':
      return value
    case 'hour':
      return value
    default:
      return value
  }
}

onLoad(option => {
  if (option.id) {
    getProductDetail({ id: option.id }).then(res => {
      goodsDetail.value = res
      swiperList.value = res.carouselImage.split(',')
      activeSpecification.value = res.mallProductSkuList[0] || {} // 默认选中第一个规格
      detail.value = (res.detail || '').replace(/<img/gi, '<img style="max-width:100%;height:auto" ')
    })
    getRoomList()
  }
})
</script>

<style scoped lang="scss">
.header-c {
  margin-bottom: 24rpx;
  .swiper-c {
    width: 750rpx;
    height: 340rpx;
  }
  .price-c {
    position: relative;
    z-index: 1;
    height: 128rpx;
    background: linear-gradient(303deg, #ff7733 0%, #ff4000 100%);
    .line1 {
      font-size: 26rpx;
      color: #ffffff;
      line-height: 40rpx;
    }
    .line2 {
      font-size: 38rpx;
      color: #ffffff;
      line-height: 58rpx;
      &::before {
        content: '￥';
        font-size: 26rpx;
      }
    }
  }
}
.specification-c {
  background: #ffffff;
  padding: 24rpx 32rpx;
  width: 686rpx;
  border-radius: 20rpx;
  margin: 0 auto;
  .title {
    font-size: 34rpx;
    color: #303133;
    line-height: 50rpx;
    margin-bottom: 16rpx;
  }
  .subtitle {
    font-weight: 400;
    font-size: 26rpx;
    color: #909399;
    line-height: 40rpx;
    border-bottom: 1px solid #e4e7ed;
  }
  .item-c {
    padding: 8rpx 0;
    margin-bottom: 16rpx;
    align-items: start;
    .label {
      width: 80rpx;
      font-size: 28rpx;
      color: #303133;
      line-height: 42rpx;
    }
    .value {
      font-weight: 400;
      font-size: 28rpx;
      color: #606266;
    }
  }
}

.action-sheet-c {
  padding-bottom: 120rpx;
  .left {
    color: #303133;
  }
  .item-c {
    height: 80rpx;
    line-height: 80rpx;
    font-size: 28rpx;
    color: #303133;
    background: #f6f9fb;
    border-radius: 48rpx 48rpx 48rpx 48rpx;
    border: 2rpx solid #f6f9fb;
    margin-bottom: 16rpx;
  }
  .active {
    background: #e5f2ff;
    border: 2rpx solid #1e90ff;
  }
  .btn-c {
    position: relative !important;
  }
}

.num-c {
  margin: 42rpx 0 38rpx 0;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  .btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 56rpx;
    height: 56rpx;
    border-radius: 10rpx;
    background: #f0f2f5;
  }
  .num {
    margin: 0 4rpx;
    width: 72rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    font-size: 24rpx;
    font-weight: 400;
    background: #f0f2f5;
  }
}
.btn-c {
  position: fixed;
  bottom: 12rpx;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 2;
  background: #fff;
  .btn {
    height: 94rpx;
    background: #1e90ff;
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    text-align: center;
    line-height: 94rpx;
    color: #fff;
    font-size: 32rpx;
  }
}
</style>
